package com.aos.erp.generator.web;

import com.aos.erp.common.bean.ResultEntity;
import com.aos.erp.generator.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Arivn
 * @createTime
 * @description
 */
@Controller
@RequestMapping("/generator")
public class GeneratorController {


    @Resource
    private GeneratorService generatorService;

    @RequestMapping("/list")
    public String list() {
        return "/generator/list";
    }

    @RequestMapping("/data/list")
    @ResponseBody
    public ResultEntity list(@RequestParam(name = "pageIndex", defaultValue = "1") long pageIndex
            , @RequestParam(name = "pageSize", defaultValue = "20") long pageSize, String tableName) {
        return ResultEntity.success(generatorService.queryList(pageIndex, pageSize, tableName));
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(@RequestParam(value = "tableNames[]", required = false) String[] tableNames, String tablePrefix, String packageName, String moduleName
            , HttpServletResponse response) throws IOException {

        byte[] data = generatorService.generatorCode(packageName, moduleName, tableNames, tablePrefix);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + moduleName + "-code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}